{% extends "base.html" %}
{% load cctags %}
{% load ccfilters %}

{% block css %}
<link type="text/css" rel="stylesheet" href="/static/styles/jqueryui/themes/base/jquery.ui.all.css"/>
<link type="text/css" rel="stylesheet" href="/static/styles/riders.css"/>
{% endblock %}

{% block scripts %}
{% if site_settings.development %}
<script type="text/javascript" src="/static/js/jqueryui/jquery-ui-1.8.13.custom.min.js"></script>
{% else %}
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.13/jquery-ui.min.js"></script>
{% endif %}
<script type="text/javascript" src="{% url views.localjavascript 'magicycle.js' %}"></script>
<script type="text/javascript" src="/static/js/jquery.imagePreview.1.0.js"></script>
<script type="text/javascript" src="/static/js/jquery.blockUI.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("img.preview_img").preview();
    $("#tabs").tabs();
    $("#search_bar_txt").focus();

    var bind_friend_button = function(){
    {% if user %}
        $(".set_as_friend").each(function(){
            $(this).unbind("click");
            $(this).click(function(){
                var set_as_friend = $(this);
                $.ajax({
                    type:"POST",
                    url:"{% url apis.apisviews.rest %}",
                    data: { method:"send_friend_request",
                        friend_uid: set_as_friend.attr("name")
                    },
                    success: function(res){
                        res = JSON.parse(res);
                        if (res.status=="ok") {
                            set_as_friend.html('{% _ "Friend Requests" %} {% _ "Sent" %}');
                        }  else{
                            alert(res.message);
                        }
                    },
                    error:function(xhr, msg){
                        alert(msg);
                    }
                });
            });
        });
    {% endif %}
    };
    bind_friend_button();

    var bind_like_button = function(){
        $("._like").each(function(){
            $(this).unbind("click");
            $(this).click(function(){
                var routeid = $(this).attr("id").replace("like_", "");
                $.post("{% url apis.apisviews.rest %}",
                        {method:"add_favorite_route",
                            routeid: routeid
                        },
                        function(data){
                            data = JSON.parse(data);
                            if (data.status=="ok") {
                                $.growlUI('{% _ "Route added into your Favorites" %}',' ');
                            } else {
                                alert(data.message);
                            }
                        });
            });
        });
    };
    bind_like_button();

    function load_more(div_loading, post_data, callback){
        div_loading.fadeIn(1000);
        $.ajax({
            type:"POST",
            url:"{% url apis.apisviews.rest %}",
            data: post_data,
            success: function(res){
                res = JSON.parse(res);
                if (res.status=="ok") {
                    callback(res);
                }  else{
                    alert(res.message);
                }
            },
            error:function(xhr, msg){
                alert(msg);
            },
            complete:function(){
                div_loading.fadeOut(1000);
            }
        });
    }


    var btn_load_more_routes = $("#load_more_routes");
    btn_load_more_routes.click(function(){
        load_more($("#routes_loading"),
                  { method:"search_routes",
                    search_text:"{{ search_text|escapejs }}",
                    pagesize: {{ pagesize.routes }},
                    start_cursor: $("#route_cursor").val()},
                  function(res){
                      var routes = res.routes;
                      $("#route_cursor").val(res.end_cursor);
                      if(routes.length < {{ pagesize.routes }}){
                          btn_load_more_routes.hide();
                      }
                      insert_routes(routes);
                  });
    });
    var insert_routes = function(routes){
        var container = $("#routes_container");
        var route_rows = $(".route_row",container);
        var total_rows = route_rows.length;
        $.each(routes, function(index, route){
            var row = $(route_rows[Math.abs(total_rows-2-index)%total_rows]).clone();
            row.attr("id", route.id);
            $(".preview_map a", row).attr("href", "{% url routes.routesviews.showallroutes %}"+route.id);
            $(".preview_map a img", row).attr("src", route.preview_url);
            $(".preview_map a img", row).attr("title", route.name);
            $(".preview_map a img", row).preview();
            $("span.value", row).html(Math.round(route.distance/1000));
            $("a.route_name", row).attr("href", "{% url routes.routesviews.showallroutes %}"+route.id);
            $("a.route_name", row).html(route.name);
            $("a._done", row).attr("href", "{% url routes.ridesviews.logride %}"+route.id);
            $("a._like", row).attr("id", "like_"+route.id);

            $("span.creator", row).empty();
            $("span.creator", row).html('{% _ "By" %} <a href="{0}">{1}</a> {% _ "Created on" %} {2}'.format(
                "{% url riders.ridersviews.ridersindex %}"+route.creator_uid, route.creator,
                formatutc(route.create_datetime, "yyyy-MM-dd")
            ));

            $("span.route_location", row).html("{0} <br/>{1} {2}".format(route.start_address, '{% _ "to" %}', route.end_address));
            container.append(row);
        });
        var routes_results = $("#routes_results");
        routes_results.text( parseInt(routes_results.text()) + routes.length);
        bind_like_button();
    };

    var btn_load_more_riders = $("#load_more_riders");
    btn_load_more_riders.click(function(){
        load_more($("#riders_loading"),
                { method:"search_riders",
                    search_text:"{{ search_text|escapejs }}",
                    pagesize: {{ pagesize.riders }},
                    start_cursor: $("#rider_cursor").val()},
                function(res){
                    var riders = res.riders;
                    $("#rider_cursor").val(res.end_cursor);
                    if(riders.length < {{ pagesize.riders }}){
                        btn_load_more_riders.hide();
                    }
                    insert_riders(riders);
                });
    });
    var insert_riders = function(riders){
        var container = $("#riders_container");
        var user_infos = $(".user_info",container);
        $.each(riders, function(index, rider){
            var new_rider = $(user_infos[0]).clone();
            $("#user_url", new_rider).attr("href", "{% url riders.ridersviews.ridersindex %}"+rider.uid);
            $("#user_url img", new_rider).attr("src", rider.photourl);
            $("#user_url img", new_rider).attr("alt", rider.uid);
            $("#grade_name", new_rider).empty();
            $("#grade_name", new_rider).attr("title", rider.point);
            for(var i=0; i<rider.suns; i++){
                $("#grade_name", new_rider).append('<img src="/static/images/sun.png"/>');
            }
            for(var i=0; i<rider.stars; i++){
                $("#grade_name", new_rider).append('<img src="/static/images/star.png"/>');
            }
            if(rider.stars<=0){
                $("#grade_name", new_rider).append('<img src="/static/images/star_half.png"/>');
            }
            $("#grade_name", new_rider).append('<a href="{0}"> {1} </a> {2} {3},{4}'.format(
                    "{% url riders.ridersviews.ridersindex %}"+rider.uid,
                    rider.name, '{% _ "From" %}', rider.city, rider.country)
            );

            $("#friend", new_rider).empty();

            $("#last_login", new_rider).html('{% _ "Last Login" %} {0}'.format(
                    formatutc(rider.last_login_datetime, "yyyy-MM-dd")));
            $("#intro", new_rider).html(rider.intro);
            $("#routes_total_distance", new_rider).html(Math.round(rider.routes_total_distance/1000));
            $("#routes_count", new_rider).html(rider.routes_count);
            $("#rides_total_distance", new_rider).html(Math.round(rider.rides_total_distance/1000));
            $("#rides_count", new_rider).html(rider.rides_count);
            $("#hours_on_bike", new_rider).html(rider.hours_on_bike.toFixed(1));
            container.append(new_rider);
        });
        var riders_results = $("#riders_results");
        riders_results.text( parseInt(riders_results.text()) + riders.length);
    };

    var btn_load_more_comments = $("#load_more_comments");
    btn_load_more_comments.click(function(){
        load_more($("#comments_loading"),
                { method:"search_comments",
                    search_text:"{{ search_text|escapejs }}",
                    pagesize: {{ pagesize.comments }},
                    start_cursor: $("#comment_cursor").val()},
                function(res){
                    var comments = res.comments;
                    $("#comment_cursor").val(res.end_cursor);
                    if(comments.length < {{ pagesize.comments }}){
                        //btn_load_more_comments.hide();
                        btn_load_more_comments.unbind("click").hide();
                    }
                    if(comments.length<=0){
                        btn_load_more_comments.parent().append('<h3>{% _ "no comment" %} {% _ "found for" %} "{{ search_text|escape }}"</h3>');
                    }
                    insert_comments(comments);
                });
    });
    var insert_comments = function(comments){
        var container = $("#comments_container");
        $.each(comments, function(index, comment){
            var li_comment = $("#comment_template",container).clone();
            li_comment.attr("id", "comment_"+comment.id);
            $("#reviewer_url", li_comment).attr("href", "{% url riders.ridersviews.ridersindex %}"+comment.reviewer_uid);
            $("#reviewer_url img", li_comment).attr("src", comment.reviewer_photourl || "/static/images/rider.jpg");
            $("#reviewer_url img", li_comment).attr("title", comment.reviewer);
            $("#comment_type img", li_comment).attr("src", '/static/images/comment_'+ comment.category +'.png');
            $("#comment_type img", li_comment).attr("title", comment.category);

            $(".comment_name", li_comment).html('<a href="{0}">{1}</a>  {2}'.format(
                    "{% url riders.ridersviews.ridersindex %}"+comment.reviewer_uid,
                    comment.reviewer,
                    formatutc(comment.posted_on, "yyyy-MM-dd hh:mm")
            ));
            $(".comment_route", li_comment).html('{0} <a href="{1}">{2}</a>'.format(
                    "{% _ 'Posted on Route' %}",
                    "{% url routes.routesviews.showallroutes %}"+comment.route_id,
                    comment.route_name
            ));
            $(".comment_content", li_comment).html("&nbsp;&nbsp;{0}".format(comment.review));
            if(comment.photourl){
                $(".comment_photo", li_comment).attr("src", comment.photourl).preview();
            }else
            {
                $(".comment_photo", li_comment).hide();
                $(".comment", li_comment).css({"width": 370})
            }
            container.append(li_comment.show());
        });
    };
});
</script>
{% endblock %}

{% block menu %}
    <li><a href="{% url views.index %}">{% _ "Home" %}</a></li>
    <li><a href="{% url routes.routesviews.showallroutes %}">{% _ "Routes" %}</a></li>
    <li><a href="{% url routes.ridesviews.showallrides %}">{% _ "Rides" %}</a></li>
    <li><a href="{% url riders.ridersviews.ridersindex %}">{% _ "Riders" %}</a></li>
    <li value="1"><a>{% _ "Search" %}</a></li>
{% endblock %}

{% block main-page %}

<div id="search_results">
    <div id="search_bar">
    <form action="{% url views.search %}" method="post" id="search_bar_search">
        <input type="text" id="search_bar_txt" name="search-txt" placeholder="{% _ "Search for Routes and Riders" %}"
               value="{{ search_text|escape }}"/>
        <input type="submit" id="search_bar_btn" value="Search" />
    </form>
    </div>
    <div class="clear"></div>
    <div id="tabs">
        <ul>
            <li><a href="#logride_route"><img class="tab_img" src="/static/images/routes.png"/>{% _ "Routes" %}
                (<span id="routes_results">{{ routes|length }}</span>)
            </a></li>
            <li><a href="#riders"><img class="tab_img" src="/static/images/rider_icon.png"/>{% _ "Riders" %}
                (<span id="riders_results">{{ riders|length }}</span>)
            </a></li>
            <li><a href="#comments"><img class="tab_img" src="/static/images/comment_text.png"/>{% _ "Comments" %}
            </a></li>
        </ul>
        <div id="logride_route">
            <div id="routes_container" class="container">
            {% for route in routes %}
                <div id="{{ route.id }}" class="route_row {%if forloop.counter0|divisibleby:2 %}alt{%endif%}" >
                    <div class="preview_map">
                        <a href="{% url routes.routesviews.showroute route.id %}">
                            <img class="preview_img" src="{{ route.preview_url|safe }}" title="{{ route.name }}"/></a>
                    </div>
                    <div class="distance">
                        <span class="value">{{ route.distance|divide:"1000"|_u|floatformat:"0" }}</span>
                        <span class="unit">{{ unit.km_mile }}</span>
                    </div>
                    <div class="title_container" style="width: 740px">
                        <span><a class="route_name" href="{% url routes.routesviews.showroute route.id %}">{{ route.name }}</a>
                            <a class="_done" href="{% url routes.ridesviews.logride route.id %}" title="{% _ 'Have Done' %}">
                                <img width="16px" height="16px" src="/static/images/done.png" alt="{% _ 'Have Done' %}"/>
                            </a>
                            <a id="like_{{ route.id }}" class="_like" href="javascript:;" title="{% _ 'Like' %}">
                                <img width="16px" height="16px" src="/static/images/like.png" alt="{% _ 'Like' %}"/>
                            </a></span>
                        <span class="creator">{% _ "By" %}
                            <a href="{% url riders.ridersviews.userpage route.Creator.uid %}">{{route.Creator.name}}</a>
                            {% _ "Created on" %}
                            {{ route.create_datetime|cctimesince }} {% _ "ago" %}
                        </span>
                        <span class="route_location">{{ route.start_address }}<br/> {% _ "to" %} {{ route.end_address }}</span>
                    </div>
                </div>
            {% endfor %}
            </div>
        {% if routes|length >= pagesize.routes %}
            <div class="clear"></div>
            <div class="div_load_more" id="load_more_routes"><a href="javascript:;">{% _ "More Routes..." %}</a></div>
        {% endif %}
        {% if not routes %}
            <h3>{% _ "no route" %} {% _ "found for" %} "{{ search_text|escape }}"</h3>
        {% endif %}
            <div id="routes_loading" class="loading"><img src="/static/images/routes_loading.gif" alt="route loadig..."/></div>
            <input name="route_cursor" id="route_cursor" type="hidden" value="{{ route_cursor }}"/>
            <div class="clear"></div>
        </div>
        <div id="riders">
            <div id="riders_container" class="container">
            {% for showuser in riders %}
                <div class="user_info">
                    <a id="user_url" href="{% url riders.ridersviews.userpage showuser.uid %}">
                    <img class="photo" src="{{ showuser.photourl|default:"/static/images/rider.jpg"|safe }}" alt="{{ showuser.name }}"/>
                    </a>
                    <div class="name_location">
                        <div id="grade_name" class="grade name" title="{{ showuser.Point }}">
                            {% for sun in showuser.Suns %}<img src="/static/images/sun.png"/>{% endfor %}
                            {% for start in showuser.Stars %}
                                <img src="/static/images/star.png"/>
                            {% empty %}
                                <img src="/static/images/star_half.png"/>
                            {% endfor %}
                             <a href="{% url riders.ridersviews.userpage showuser.uid %}">
                                {{ showuser.name }}</a> {% _ "From" %}
                                {% if showuser.country %} {{ showuser.city }},{{ showuser.country }}{% else %}{% _ "Unknown" %} {% endif %}
                        </div>
                        <p id="last_login">{% _ "Last Login" %} {{ showuser.last_login_datetime|cctimesince }} {% _ "ago" %}</p>
                        {% if user %}
                        <div id="friend" >
                            {% if showuser.uid == user.uid %}
                                <p><a href="{% url riders.ridersviews.editprofile user.uid %}">{% _ "Edit Your Profile" %}</a></p>
                            {% else %}
                                {% if showuser.key_name not in user.friends %}
                                    {% if user.key_name in showuser.friendrequestlist %}
                                       <p>{% _ "Friend Requests" %} {% _ "Sent" %}</p>
                                    {% else %}
                                        <p class="set_as_friend" name="{{ showuser.uid }}"><a href="javascript:;">{% _ "Add as friend" %}</a></p>
                                    {% endif %}
                                {% else %}
                                    <p>{% _ "Friend" %}</p>
                                {% endif %}
                            {% endif %}
                        </div>
                        {% endif %}
                        <p id="intro" class="intro">{{ showuser.intro }}</p>
                    </div>
                    <div class="stats">
                        <ul>
                            <li>
                                <b id="routes_total_distance">{{ showuser.Stats.routes_total_distance|divide:"1000"|_u|floatformat:"0" }}</b>
                                {{ unit.km_mile }},
                                <b id="routes_count">{{ showuser.Stats.routes_count }}</b> {% _ "Routes" %}
                            </li>
                            <li>
                                <b id="rides_total_distance">{{ showuser.Stats.rides_total_distance|divide:"1000"|_u|floatformat:"0" }}</b>
                                {{ unit.km_mile }},
                                <b id="rides_count">{{ showuser.Stats.rides_count }}</b> {% _ "Rides" %}
                            </li>
                            <li>
                                <b id="hours_on_bike">{{ showuser.Stats.hours_on_bike|floatformat:"1" }}</b>
                                {% _ "hours" %} {% _ "on bike" %}
                            </li>
                        </ul>
                    </div>
                </div>
            {% endfor %}
            </div>
            {% if riders|length >= pagesize.riders %}
            <div class="clear"></div>
            <div class="div_load_more" id="load_more_riders"><a href="javascript:;">{% _ "More Riders..." %}</a></div>
            {% endif %}
            {% if not riders %}
                <h3>{% _ "no rider" %} {% _ "found for" %} "{{ search_text|escape }}"</h3>
            {% endif %}
            <div id="riders_loading" class="loading"><img src="/static/images/routes_loading.gif" alt="riders loadig..."/></div>
            <input id="rider_cursor" name="rider_cursor" type="hidden" value="{{ rider_cursor }}"/>
            <div class="clear"></div>
        </div>
        <div id="comments">
            <div id="comments_container" class="container">
                <li id="comment_template" style="display: none">
                    <div class="comment_header">
                        <p><a id="reviewer_url" href=""><img alt="comment.reviewer"/></a></p>
                        <p id="comment_type"><img alt="comment.type"/></p>
                    </div>
                    <div class="comment">
                        <div class="comment_name">comment.reviewer + comment.posted_on</div>
                        <div class="comment_route">on comment.route_name</div>
                        <div class="comment_content">comment.review</div>
                    </div>
                    <img class="comment_photo"/>
                </li>
            </div>
            <div class="clear"></div>
            <div class="div_load_more" id="load_more_comments"><a href="javascript:;">{% _ "Load Comments..." %}</a></div>
            <div id="comments_loading" class="loading"><img src="/static/images/routes_loading.gif" alt="comments loadig..."/></div>
            <input id="comment_cursor" name="comment_cursor" type="hidden" value=""/>
            <div class="clear"></div>
        </div>
    </div>
    <div style="clear: both;">&nbsp;</div>

</div>
{% endblock %}
